<script setup>
import { computed, onMounted, ref } from "vue";
import { ElMessage } from 'element-plus';
import { ArrowDown, ArrowUp } from "@element-plus/icons-vue";
import { useRouter } from 'vue-router';

const props = defineProps(['postId', 'info']);
const emit = defineEmits(['updateCommentCount']);
const router = useRouter();

// 评论列表
const commentList = ref([]);
const textarea = ref("");
const textareaCount = computed(() => 100 - textarea.value.length);

onMounted(async () => {
  await fetchComments();
});

// 获取评论列表
const fetchComments = async () => {
  const res = await fetch(`/api/post/comments/${props.postId}?account=${localStorage.getItem('account')}`);
  const data = await res.json();

}

// 发表评论
const submitComment = async () => {
  if (!textarea.value.trim()) {
    ElMessage.error("评论不能为空");
    return;
  }

  try {
    const res = await fetch('/api/post/comment', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        postId: props.postId,
        account: localStorage.getItem('account'),
        content: textarea.value
      })
    });

    if (res.ok) {
      ElMessage.success("发布评论成功！");
      textarea.value = '';
      emit('updateCommentCount');
      await fetchComments();
    }
  } catch (error) {
    ElMessage.error('评论失败');
  }
};

// 处理点赞/取消点赞
const like = async (comment) => {
  try {
    const res = await fetch('/api/post/comment/like', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        commentId: comment.id,
        account: localStorage.getItem('account')
      })
    });

    if (res.ok) {
      ElMessage.success("点赞成功");
      comment.isLiked = true;
      comment.likeCount++;
    }
  } catch (error) {
    ElMessage.error('点赞失败');
  }
};

const unlike = async (comment) => {
  try {
    const res = await fetch('/api/post/comment/unlike', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        commentId: comment.id,
        account: localStorage.getItem('account')
      })
    });

    if (res.ok) {
      ElMessage.success("取消点赞成功！");
      comment.isLiked = false;
      comment.likeCount--;
    }
  } catch (error) {
    ElMessage.error('取消点赞失败');
  }
};

// 回复相关��法
const openReply = (comment) => {
  comment.isReply = true;
};

const closeReply = (comment) => {
  comment.isReply = false;
};

const reply = async (comment, parentId) => {
  if (!comment.reply?.trim()) {
    ElMessage.error("回复不能为空");
    return;
  }

  try {
    const res = await fetch('/api/post/comment/reply', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        postId: props.postId,
        parentId: parentId,
        account: localStorage.getItem('account'),
        content: comment.reply
      })
    });

    if (res.ok) {
      ElMessage.success("回复成功！");
      comment.isReply = false;
      comment.reply = '';
      emit('updateCommentCount');
      await fetchComments();
    }
  } catch (error) {
    ElMessage.error('回复失败');
  }
};

const expandReply = async (comment) => {
  comment.isExpand = !comment.isExpand;
  if (comment.isExpand && !comment.replyList) {
    try {
      const res = await fetch(`/api/post/comments/replies/${comment.id}?account=${localStorage.getItem('account')}`);
      const data = await res.json();
      if (data.code === 200) {
        comment.replyList = data.data;
      }
    } catch (error) {
      ElMessage.error('获取回复失败');
    }
  }
};

const collectDialogVisible = ref(false)
const favoriteList = ref([]) // 收藏夹列表
const selectedFavorite = ref(null) // 当前选中的收藏夹
const newFavoriteName = ref('') // 新建收藏夹名称
const showCreateInput = ref(false) // 是否显示创建收藏夹输入框

// 打开收藏对话框
const openCollectMark = async () => {
  collectDialogVisible.value = true
  // 获取用户的收藏夹列表
  try {
    const res = await fetch(`/api/favorites?account=${localStorage.getItem('account')}`)
    const data = await res.json()
    if (data.code === 200) {
      favoriteList.value = data.data
    }
  } catch (error) {
    ElMessage.error('获取收藏夹失败')
  }
}

// 创建新收藏夹
const createNewFavorite = async () => {
  if (!newFavoriteName.value.trim()) {
    ElMessage.warning('请输入收藏夹名称')
    return
  }
  
  try {
    const res = await fetch('/api/favorites', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        name: newFavoriteName.value,
        account: localStorage.getItem('account')
      })
    })
    
    if (res.ok) {
      ElMessage.success('创建成功')
      showCreateInput.value = false
      newFavoriteName.value = ''
      // 刷新收藏夹列表
      const newList = await fetch(`/api/favorites?account=${localStorage.getItem('account')}`)
      const data = await newList.json()
      if (data.code === 200) {
        favoriteList.value = data.data
      }
    }
  } catch (error) {
    ElMessage.error('创建失败')
  }
}

// 确认收藏
const confirmCollect = async () => {
  if (!selectedFavorite.value) {
    ElMessage.warning('请选择收藏夹')
    return
  }
  
  try {
    const res = await fetch('/api/favorites/collect', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        favoriteId: selectedFavorite.value,
        postId: props.postId,
        account: localStorage.getItem('account')
      })
    })
    
    if (res.ok) {
      ElMessage.success('收藏成功')
      collectDialogVisible.value = false
    }
  } catch (error) {
    ElMessage.error('收藏失败')
  }
}
</script>

<template>
  <div class="comment-area">
    <h2 style="display: inline-block;font-weight: normal">评论</h2>
    <span style="display: inline-block;margin-left: 12px;font-size: 14px;color: #999999">
      共{{ info.commentNum }}条评论
    </span>

    <div style="box-sizing: border-box;margin-top: 15px;overflow: hidden;height: 103.6px;width:857px;position: relative">
      <textarea
        placeholder="说说你的看法吧"
        v-model="textarea"
      ></textarea>
      <div v-if="textareaCount >= 0" style="color: #999999;font-size: 14px;position: absolute;bottom: 5px;right: 10px">
        剩余<span style="font-weight: 200;color: #e96161">{{ textareaCount }}</span>字
      </div>
      <div v-else style="color: #999999;font-size: 14px;position: absolute;bottom: 5px;right: 10px">
        超过<span style="font-weight: 200;color: #e96161">{{ -textareaCount }}</span>字
      </div>
    </div>
    <button @click="submitComment" class="sendComment-button">发表评论</button>

    <h3 style="margin-top: 60px;height: 60px;line-height: 60px;color: black;border-bottom: 1px solid #e3e3e3;font-size: 16px;font-weight: normal">
      全部评论({{ info.commentNum }})
    </h3>

    <div v-for="comment in commentList"
         :key="comment.id"
         style="border-bottom: 1px solid #e3e3e3;display: flex;gap: 15px;padding: 15px 0 30px 15px;width: 857px;box-sizing: border-box;">
      <img
        style="margin-top: 2px;width: 40px;height: 40px;border-radius: 50%"
        :src="comment.avatar || '/src/assets/img/icon.png'"
      >
      <div style="display: flex;width: 787px;word-wrap: break-word;flex-direction: column;color: #999;font-size: 14px">
        <div class="hover" style="line-height: 26px;height: 26px">
          {{ comment.username }}
        </div>
        <div style="height: 20px;line-height: 20px">{{ comment.commentTime }}</div>
        <div style="margin-bottom: 4px;white-space: pre-wrap;margin-top: 13px;color: black;line-height: 26px">
          {{ comment.content }}
        </div>

        <div style="display: flex;align-items: center;gap: 20px">
          <div @click="unlike(comment)"
               style="display: flex;font-weight: 1;align-items: center;color: #e96161"
               v-if="comment.isLiked">
            <i class="comment-liked-icon"></i>
            <div v-if="comment.likeCount > 0">{{ comment.likeCount }}</div>
          </div>
          <div @click="like(comment)"
               style="display: flex;font-weight: 1;align-items: center;color: black"
               v-else>
            <i class="comment-like-icon"></i>
            <div v-if="comment.likeCount > 0">{{ comment.likeCount }}</div>
          </div>
          <div class="hover" @click="openReply(comment)">回复</div>
        </div>

        <!-- 回复框 -->
        <div v-if="comment.isReply">
          <div style="margin-top: 15px;overflow: hidden;height: 103.6px;width:800px;position: relative">
            <textarea
              placeholder="说说你的看法吧"
              v-model="comment.reply"
              style="width: 787px!important;min-height: 100px;box-sizing: border-box"
            ></textarea>
            <div v-if="!comment.reply"
                 style="color: #999999;font-size: 14px;position: absolute;bottom: 7px;right: 20px">
              剩余<span style="font-weight: 200;color: #e96161">100</span>字
            </div>
            <div v-else-if="comment.reply.length <= 100"
                 style="color: #999999;font-size: 14px;position: absolute;bottom: 7px;right: 20px">
              剩余<span style="font-weight: 200;color: #e96161">{{ 300 - comment.reply.length }}</span>字
            </div>
            <div v-else
                 style="color: #999999;font-size: 14px;position: absolute;bottom: 7px;right: 20px">
              超过<span style="font-weight: 200;color: #e96161">{{ comment.reply.length-300 }}</span>字
            </div>
          </div>
          <div>
            <button style="margin-left: auto"
                    @click="closeReply(comment)"
                    class="cancelComment-button">取消</button>
            <button style="margin-left: auto;margin-right: 6px"
                    @click="reply(comment, comment.id)"
                    class="sendComment-button">回复</button>
          </div>
        </div>

        <!-- 展开回复 -->
        <div @click="expandReply(comment)"
             v-if="comment.commentNum > 0"
             class="hover"
             style="margin-top: 2px;display: flex;align-items: flex-end;gap: 5px">
          查看{{ comment.commentNum }}条回复
          <el-icon v-if="comment.isExpand" style="font-size: 16px"><ArrowUp /></el-icon>
          <el-icon v-else style="font-size: 16px"><ArrowDown /></el-icon>
        </div>

        <!-- 回复列表 -->
        <div v-if="comment.isExpand" class="replyArea">
          <!-- 递归渲染回复内容，与主评论结构类似 -->
        </div>
      </div>
    </div>
  </div>

  <el-dialog
    v-model="collectDialogVisible"
    title="添加收藏"
    width="400px"
    :close-on-click-modal="false"
    :show-close="true"
  >
    <div class="collect-dialog-content">
      <!-- 收藏夹列表 -->
      <div class="favorite-list">
        <div v-for="item in favoriteList" 
             :key="item.id"
             class="favorite-item"
             :class="{ 'active': selectedFavorite === item.id }"
             @click="selectedFavorite = item.id"
        >
          <div class="favorite-info">
            <span class="favorite-name">{{ item.name }}</span>
            <span class="favorite-count">{{ item.count }}个内容</span>
          </div>
          <el-radio v-model="selectedFavorite" :label="item.id" />
        </div>
      </div>

      <!-- 创建新收藏夹 -->
      <div v-if="showCreateInput" class="create-favorite">
        <el-input
          v-model="newFavoriteName"
          placeholder="请输入收藏夹名称"
          maxlength="20"
          show-word-limit
        >
          <template #append>
            <el-button @click="createNewFavorite">创建</el-button>
          </template>
        </el-input>
      </div>
      
      <div v-else class="create-favorite-btn" @click="showCreateInput = true">
        <i class="el-icon-plus"></i>
        <span>新建收藏夹</span>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="collectDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCollect">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.replyArea {
  width: 787px;
  box-sizing: border-box;
  margin-top: 10px;
  padding: 10px 20px;
  background-color: rgba(0, 0, 0, 0.05);
}

.hover:hover {
  cursor: pointer;
  color: #ff8763;
}

.sendComment-button {
  color: white;
  background-color: #ff8563;
  border: 0;
  float: right;
  text-align: center;
  width: 81px;
  line-height: 28px;
  height: 28px;
  margin-top: 12px;
  border-radius: 2px;
  font-size: 14px;
  cursor: pointer;
}

.cancelComment-button {
  background-color: white;
  border: 1px solid #d5d5d5;
  float: right;
  text-align: center;
  width: 81px;
  line-height: 27px;
  height: 28px;
  margin-top: 12px;
  border-radius: 2px;
  font-size: 14px;
  cursor: pointer;
}

textarea {
  resize: none;
  outline: none;
  min-height: 66px;
  width: 827.4px;
  display: block;
  padding: 18.8px 14.8px;
  color: #333;
  font-size: 14px;
  font-family: poppin, Tahoma, Arial, 微软雅黑, sans-serif;
  white-space: pre-wrap;
  border: 1px solid #ececec;
  background-color: #f5f5f5;
}

.comment-area {
  margin-top: 70px;
  width: 857px;
  font-family: poppin, Tahoma, Arial, \5FAE\8F6F\96C5\9ED1, sans-serif!important;
}

i:not(.el-icon) {
  width: 34px;
  height: 34px;
  display: inline-block;
  background: url("/src/assets/img/total2.png") no-repeat;
  margin-left: -6px;
  margin-right: -2px;
}

.comment-liked-icon {
  background-position: 0 -50px!important;
  scale: 0.5;
  cursor: pointer;
}

.comment-like-icon {
  background-position: -50px -50px!important;
  scale: 0.5;
  cursor: pointer;
}

img {
  cursor: pointer;
}

.collect-dialog-content {
  min-height: 300px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.favorite-list {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.favorite-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.favorite-item:hover {
  background-color: #f5f5f5;
}

.favorite-item.active {
  background-color: #e6f4ff;
}

.favorite-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.favorite-name {
  font-size: 14px;
  color: #333;
}

.favorite-count {
  font-size: 12px;
  color: #999;
}

.create-favorite {
  padding: 16px;
  border-top: 1px solid #f0f0f0;
}

.create-favorite-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  color: #1890ff;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.create-favorite-btn:hover {
  background-color: #f0f7ff;
}

.dialog-footer {
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
  text-align: right;
}
</style>
